package com.huitongmaoyi.ai;

import com.huitongmaoyi.ai.dao.CustomerDAO;
import com.huitongmaoyi.ai.dao.UserDAO;
import com.huitongmaoyi.ai.entity.Customer;
import com.huitongmaoyi.ai.service.AIAnalysisService;
import com.huitongmaoyi.ai.service.AuthService;
import com.huitongmaoyi.ai.service.ChatService;
import com.huitongmaoyi.ai.service.CustomerService;

import java.io.*;
import java.net.Socket;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.ConcurrentHashMap;

public class UserSessionHandler implements Runnable {
    public static Map<String, UserSessionHandler> onlineUsers = new ConcurrentHashMap<>();

    private final Socket clientSocket;
    private BufferedReader in;
    private PrintWriter out;
    private String currentUsername;
    private final AuthService auth = new AuthService();
    private final UserDAO userDAO = new UserDAO();
    private AIAnalysisService aiAnalysisService;
    private long currentChatRoom = -1; // 当前所在聊天室ID，-1表示不在聊天室

    private enum UserState {
        LOGIN, MAIN_MENU, CHAT_SYSTEM
    }
    private UserState currentState = UserState.LOGIN;

    public UserSessionHandler(Socket socket) {
        this.clientSocket = socket;
    }

    @Override
    public void run() {
        try {
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            out = new PrintWriter(clientSocket.getOutputStream(), true);

            while (true) {
                switch (currentState) {
                    case LOGIN:
                        handleLoginStage();
                        break;
                    case MAIN_MENU:
                        handleMainMenuStage();
                        break;
                    case CHAT_SYSTEM:
                        handleChatSystemStage();
                        break;
                }
            }

        } catch (IOException e) {
            System.err.println((currentUsername != null ? currentUsername : "未知用户") + " 会话异常：" + e.getMessage());
        } finally {
            if (currentUsername != null) {
                onlineUsers.remove(currentUsername);
                System.out.println(currentUsername + " 已离线，当前在线：" + onlineUsers.keySet());
            }
            try {
                clientSocket.close();
            } catch (IOException e) {
                System.err.println("关闭连接失败：" + e.getMessage());
            }
        }
    }

    // 登录/注册阶段
    private void handleLoginStage() throws IOException {
        out.println("=== 欢迎使用慧通贸易 AI 系统 ===");

        while (currentState == UserState.LOGIN) {
            out.println("\n请选择操作：");
            out.println("1. 登录");
            out.println("2. 注册新账号");
            out.println("3. 退出");
            out.println("请输入选项（1/2/3）: ");

            String choice = in.readLine();
            if (choice == null) break;
            choice = choice.trim();

            switch (choice) {
                case "1":
                    out.println("请输入用户名: ");
                    String username = in.readLine();
                    if (username == null || username.trim().isEmpty()) {
                        out.println("\n❌ 用户名不能为空！");
                        break;
                    }
                    username = username.trim();

                    out.println("请输入密码: ");
                    String password = in.readLine();
                    if (password == null || password.trim().isEmpty()) {
                        out.println("\n❌ 密码不能为空！");
                        break;
                    }
                    password = password.trim();

                    if (auth.login(username, password)) {
                        currentUsername = username;
                        onlineUsers.put(username, this);
                        out.println("\n🎉 欢迎进入系统，" + username + "！");
                        currentState = UserState.MAIN_MENU;
                    } else {
                        out.println("\n❌ 登录失败！用户名或密码错误，请重试。");
                    }
                    break;

                case "2":
                    out.println("\n设置用户名: ");
                    String regUser = in.readLine();
                    if (regUser == null || regUser.trim().isEmpty()) {
                        out.println("\n❌ 用户名不能为空！");
                        break;
                    }
                    regUser = regUser.trim();

                    out.println("设置密码: ");
                    String regPwd = in.readLine();
                    if (regPwd == null || regPwd.trim().isEmpty()) {
                        out.println("\n❌ 密码不能为空！");
                        break;
                    }
                    regPwd = regPwd.trim();

                    if (auth.register(regUser, regPwd)) {
                        out.println("\n✅ 注册成功！用户名：" + regUser);
                    } else {
                        out.println("\n❌ 注册失败！用户名已存在，请重试。");
                    }
                    break;

                case "3":
                    out.println("\n👋 再见！");
                    clientSocket.close();
                    return;

                default:
                    out.println("\n❌ 无效选项，请输入 1、2 或 3。");
            }
        }
    }

    // 主菜单阶段
    private void handleMainMenuStage() throws IOException {
        while (currentState == UserState.MAIN_MENU) {
            out.println("\n请选择操作：");
            out.println("1. 查看所有客户");
            out.println("2. 使用 AI 智能匹配客户");
            out.println("3. 使用 AI 智能分析（自由对话）");
            out.println("4. 聊天系统");
            out.println("5. 退出");
            out.println("请输入选项：");

            String choice = in.readLine();
            if (choice == null) break;
            choice = choice.trim();

            switch (choice) {
                case "1":
                    showAllCustomers();
                    break;

                case "2":
                    out.println("\n=== AI 智能匹配客户 ===");
                    out.println("提示：输入「返回」退出当前功能");
                    new CustomerService(out).startConversation(new Scanner(in));
                    out.println("\n✅ 已退出 AI 智能匹配，返回主菜单。");
                    break;

                case "3":
                    if (aiAnalysisService == null) {
                        aiAnalysisService = new AIAnalysisService(new Scanner(in), out);
                    }
                    aiAnalysisService.startConversation();
                    break;

                case "4":
                    new ChatService(new Scanner(in), currentUsername, this).startChat();
                    break;

                case "5":
                    out.println("\n再见！");
                    clientSocket.close();
                    return;

                default:
                    out.println("\n❌ 无效选项，请重新输入！");
            }
        }
    }

    private void handleChatSystemStage() throws IOException {
        out.println("\n=== 聊天系统 ===");
        out.println("2. 与系统用户聊天（在线：" + UserSessionHandler.onlineUsers.keySet() + "）");
        out.println("3. 聊天室功能");
        out.println("4. 返回主菜单");
        out.println("请选择：");
    }

    private void showAllCustomers() throws IOException {
        CustomerDAO dao = new CustomerDAO();
        List<Customer> customers = dao.getAllCustomers();

        if (customers.isEmpty()) {
            out.println("⚠️  暂无客户数据。请先插入测试数据到 `customers` 表。");
        } else {
            out.println("\n📋 客户列表（共 " + customers.size() + " 条）：");
            out.println("-".repeat(110));
            for (Customer c : customers) {
                out.println(c);
            }
            out.println("-".repeat(110));
        }
    }

    private void showChatMenu() {
        out.println("\n聊天系统功能：");
        out.println("1. list - 查看在线用户");
        out.println("2. @用户名 消息 - 发送私聊");
        out.println("3. 返回 - 退出聊天系统");
    }

    private void showOnlineUsers() {
        out.println("\n当前在线用户：" + onlineUsers.keySet());
    }

    private void handlePrivateChat(String input) {
        try {
            int spaceIndex = input.indexOf(' ');
            if (spaceIndex == -1 || spaceIndex == input.length() - 1) {
                out.println("❌ 格式错误！正确格式：@用户名 消息内容（例：@admin 你好）");
                return;
            }

            String targetUsername = input.substring(1, spaceIndex).trim();
            String message = input.substring(spaceIndex + 1).trim();

            if (targetUsername.equals(currentUsername)) {
                out.println("❌ 不能给自己发送私聊消息！");
                return;
            }

            UserSessionHandler targetSession = UserSessionHandler.onlineUsers.get(targetUsername);
            if (targetSession == null) {
                out.println("❌ 用户「" + targetUsername + "」不在线或不存在！");
                return;
            }

            targetSession.getOut().println("\n📩 来自「" + currentUsername + "」的私聊：" + message);
            out.println("✅ 已发送私聊给「" + targetUsername + "」：" + message);

        } catch (Exception e) {
            out.println("❌ 私聊发送失败：" + e.getMessage());
        }
    }

    // 新增 getter 和 setter 方法
    public PrintWriter getOut() {
        return out;
    }

    public String getCurrentUsername() {
        return currentUsername;
    }

    public long getCurrentChatRoom() {
        return currentChatRoom;
    }

    public void setCurrentChatRoom(long currentChatRoom) {
        this.currentChatRoom = currentChatRoom;
    }
}